package com.isoftstone.framework.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.isoftstone.framework.druid.dynamicDataSource.MyDynamicDataSource;
import com.isoftstone.common.utils.SpringContext;

import java.util.HashMap;
import java.util.Map;

public class DataSourceUtil {

    public static final Map<Object, Object> dataSourceMap = new HashMap<>();

    public static void initDataSource() {
        //获取masterDataSource
        DruidDataSource masterDataSource = (DruidDataSource) SpringContext.getBean("masterDataSource");
        addDataSource("master", masterDataSource);
        //刷新数据源
        flushDataSource();
    }

    public static void flushDataSource() {
        //获取spring管理的dynamicDataSource
        MyDynamicDataSource myDynamicDataSource = (MyDynamicDataSource) SpringContext.getBean("dynamicDataSource");
        //将数据源设置到 targetDataSources
        myDynamicDataSource.setTargetDataSources(dataSourceMap);
        //将 targetDataSources 中的连接信息放入 resolvedDataSources 管理
        myDynamicDataSource.afterPropertiesSet();
    }

    public static void addDataSource(String key, DruidDataSource masterDataSource) {
        dataSourceMap.put(key, masterDataSource);
    }


}
